/**
 * Project Name:FinancingP2p
 * File Name:PublicMethod.java
 * Package Name:com.longcai.financingp2p.utils
 * Date:2015-7-22上午10:33:26
 * Copyright (c) 2015, chenzhou1025@126.com All Rights Reserved.
 */

package com.lc.user.express.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @ClassName:PublicMethod
 * @Function: TODO
 * @Date: 2015-7-22 上午10:33:26
 * @since JDK 1.6
 */
public class PublicMethod {
    private final static Pattern mobilePhonePatten = Pattern.compile("(1[3|4|5|7|8][0-9]\\d{8})");

    /**
     * @param @param  phoneNo
     * @param @return
     * @return boolean
     * @throws
     * @Title: isMobilePhone
     * @Description: TODO验证是否是手机号
     */
    public static boolean isMobilePhone(String phoneNo) {
        return mobilePhonePatten.matcher(phoneNo).matches();
    }

    /**
     * @param mobile
     * @return
     * @Title: formatMobile
     * @Description: TODO 隐藏手机号中间四位
     * @author Administrator
     * @date: 2015-7-27 下午4:41:57
     */
    public static String formatMobile(String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(mobile.substring(0, 3)).append("****")
                .append(mobile.substring((mobile.length() - 4), mobile.length()));
        return sb.toString();

    }

    /**
     * @param time1
     * @param time2
     * @return
     * @Title: time
     * @Description: TODO 时间差
     * @author Administrator
     * @date: 2015-7-28 下午1:56:01
     */
    @SuppressLint("SimpleDateFormat")
    public static long time(String time1, String time2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        long days = 0;
        try {
            Date d1 = df.parse(time1);
            Date d2 = df.parse(time2);
            long diff = d2.getTime() - d1.getTime();
            days = diff / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

    public static String formatNumber(String str) {
        DecimalFormat df = new DecimalFormat("###,###");
        return df.format(Double.parseDouble(str));
    }

    public static boolean isSdcardAvaiable() {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            Log.i("TestFile", "SD card is not avaiable/writeable right now.");
            return false;
        }
        return true;
    }

    public final static void callPhone(Context context, String phoneNumber) {
        Intent call = new Intent(Intent.ACTION_DIAL);
        call.setData(Uri.parse("tel:" + phoneNumber));
        context.startActivity(call);
    }

    public static boolean isNumAndLetter(String str) {
        if (!str.matches("^[0-9a-zA-Z]+$")) {
            return false;
        } else {
            return true;
        }
    }

    public static double strToDouble(String str) {
        try {
            if (TextUtils.isEmpty(str) || "null".equals(str)) {
                return 0;
            } else {
                return Double.valueOf(str);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (!TextUtils.isEmpty(str)) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static boolean isPassword(String str) {
        if (!str.matches("^[0-9a-zA-Z]+$")) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 把LatLng对象转化为LatLonPoint对象
     */
    public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
        return new LatLonPoint(latlon.latitude, latlon.longitude);
    }

    /**
     * 把LatLonPoint对象转化为LatLon对象
     */
    public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
        return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
    }

    public static void reStartApp(Context context) {
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        launchIntent.putExtra("restart", true);
        context.startActivity(launchIntent);
    }

    public static boolean formatDecimal(String str) {
        if (str.matches("^(?!0+(?:\\.0+)?$)(?:[1-9]\\d*|0)(?:\\.\\d{1,2})?+|$")) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 银行卡号校验
     */
    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        if(bit == 'N'){
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }
    public static char getBankCardCheckCode(String nonCheckCodeCardId){
        if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if(j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
    }
}
